<?php

declare(strict_types=1);

namespace WanZ\App\User\GrpcService;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Context\Context;
use WanZ\App\User\Grpc\Auth\AuthServiceInterface;
use WanZ\App\User\Grpc\Auth\AuthLoginResponseEntity;
use WanZ\App\User\Grpc\Auth\AuthLoginRequest;
use WanZ\App\User\Grpc\Auth\AuthLoginResponse;
use WanZ\App\User\Grpc\Auth\AuthSendCodeRequest;
use WanZ\App\User\Grpc\Auth\AuthSendCodeResponse;
use WanZ\App\User\Logic\UserLogic;
use WanZ\App\User\Logic\SmsLogic;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

class AuthGrpc implements AuthServiceInterface
{
    /**
     * @Inject
     * @var UserLogic
     */
    private $userLogic;

    /**
     * @Inject
     * @var SmsLogic
     */
    private $smsLogic;   

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;  

    public function login(AuthLoginRequest $request)
    {
        ## 请求参数
        $authCode = (string) $request->getAuthCode();
        $loginType = (string) $request->getLoginType();
        $companyId = (int) $request->getCompanyId();
        $miniSource = (string) $request->getMiniSource() ?: 'wz';
        
        $response = new AuthLoginResponse();
        try {
            Context::set('minSource', $miniSource);

            $data = $this->userLogic->login($loginType, $authCode, $companyId);
            $response->setCode(200)
                    ->setMsg('Success')
                    ->setData($data);

        } catch (\Throwable $e) {
            $this->logger->error(sprintf('%s [%s] %s', '用户登录失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());

            $response->setCode(ErrorCode::SERVER_ERROR)->setMsg('Failure')->setData('用户登录失败');
        }

		return $response;
    }

    public function sendCode(AuthSendCodeRequest $request)
    {
        ## 请求参数
        $phone = (string) $request->getPhone();
        $companyId = (int) $request->getCompanyId();
		$type = (string) $request->getType();

        $response = new AuthSendCodeResponse();
        try {
            $this->smsLogic->sendCode($phone, $type, $companyId);
            
            $response->setCode(200)
                    ->setMsg('Success')
                    ->setData('');

        } catch (\Throwable $e) {
            $this->logger->error(sprintf('%s [%s] %s', '发送短信失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());

            $response->setCode(ErrorCode::SERVER_ERROR)->setMsg('Failure')->setData('发送短信失败');
        }

		return $response;        
    }   
}
